from rest_framework import serializers
from rest_framework.response import Response
from goods.models import SKUImage, SKU
from fdfs_client.client import Fdfs_client
from django.conf import settings
from celery_tasks.static_tasks.task import get_detail_html


class ImageSerializer(serializers.ModelSerializer):
    #  返回图片关联的sku的id值
    sku = serializers.PrimaryKeyRelatedField(read_only=True)
    class Meta:
        model = SKUImage
        # fields = ('sku','image', 'id')
        fields = '__all__'

    def create(self, validated_data):

        #  创建FastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        #  获取前端传来的image文件
        data = self.context['request'].FILES.get('image')
        # data = request.data
        #  上传图片到fastDFS
        res = client.upload_by_buffer(data.read())
        #  判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        #  获取上传后的路径
        image_url = res['Remote file_id']
        #  获取sku_id
        sku_id = self.context['request'].data.get('sku')[0]
        #  保存图片
        img = SKUImage.objects.create(sku_id=sku_id,image=image_url)

        # 异步生成详情页静态页面
        get_detail_html.delay(img.sku.id)

        return img

    def update(self, instance, validated_data):

        #  创建FastDFS链接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        #  获取前端传递的image文件
        data = self.context['request'].FILES.get('image')
        #  上传图片到fastdfs
        res = client.upload_by_buffer(data.read())
        #  判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)

        # 6、更新图片表
        instance.image = res['Remote file_id']
        instance.save()

        # 异步生成详情页静态页面
        get_detail_html.delay(instance.sku.id)
        return instance


class SKUSerializer(serializers.ModelSerializer):
    """
    sku序列化器
    """
    class Meta:
        model = SKU
        fields = ('id', 'name')